<template>
  <div class="note-page">
    <!-- 上部分 -->
    <div class="header">
      <div class="title">简易笔记</div>
      <div class="actions">
        <el-button icon="el-icon-search" circle @click="showSearchDialog = true"></el-button>
        <el-button icon="el-icon-plus" circle @click="addNote"></el-button>
      </div>
    </div>

    <!-- 中间内容区 -->
    <div class="content">
      <div  v-if="filteredNotes.length != 0">
        <el-card v-for="note in filteredNotes" :key="note.id" class="note-card">
          <div class="note-content">
            <div class="note-main" @click="editNote(note)">
              <h3 class="note-title">{{ note.title }}</h3>
              <p class="note-summary">{{ note.summary }}</p>
              <p class="note-time">{{ note.date }}</p>
            </div>
            <div class="note-delete">
              <el-button type="danger" icon="el-icon-delete" @click="deleteNote(note)" class="delete-button"></el-button>
            </div>
          </div>
        </el-card>
      </div>
      <div v-else class="note-no-content">
        暂未新建笔记
      </div>
    </div>

    <!-- 下部分菜单栏 -->
    <div class="footer">
      <el-menu mode="horizontal" class="footer-menu" :default-active="currentMenuItem">
        <el-menu-item index="1">笔记</el-menu-item>
        <el-menu-item index="2">我的</el-menu-item>
        <!-- 可以在此添加更多菜单项 -->
      </el-menu>
    </div>

    <!-- 弹出层 -->
    <el-dialog
        title="检索笔记"
        :visible.sync="showSearchDialog"
        width="100%"
        :fullscreen="false"
        class="search-dialog"
        :before-close="handleClose"
    >
      <div class="dialog-content">
        <div class="input-container"> <!-- 输入框容器 -->
          <el-input
              v-model="searchQuery"
              placeholder="请输入标题关键字"
              clearable
              @input="filterNotes"
          ></el-input>
        </div>
        &nbsp;
        <div class="button-container"> <!-- 按钮容器 -->
          <el-button type="primary" @click="showSearchDialog = false">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import IndexedDBUtil from "@/utils/IndexDB";

export default {
  name: 'noteApp',
  data() {
    return {
      currentMenuItem: '1',
      notes: [],
      showSearchDialog: false,
      searchQuery: '',
      filteredNotes: [],
      dbUtil: null,  // IndexedDB 工具类实例
    };
  },
  created() {
    this.dbUtil = new IndexedDBUtil('NotesDatabase', 'NotesStore');
    this.getAllNote()
  },
  methods: {
    filterNotes() {
      if (this.searchQuery.trim() === '') {
        this.filteredNotes = this.notes;
      } else {
        const query = this.searchQuery.toLowerCase();
        this.filteredNotes = this.notes.filter(note =>
            note.title.toLowerCase().includes(query)
        );
      }
    },
    safeSubstring(str, start, end) {
      // 检查起始位置和结束位置是否有效
      if (start < 0 || end < 0 || start >= str.length) {
        return ''; // 返回空字符串
      }
      // 如果结束位置超出字符串长度，调整结束位置
      if (end > str.length) {
        end = str.length;
      }
      return str.substring(start, end);
    },
    deleteNote(note) {
      this.$confirm('确认删除?', '确认信息', {
        type: 'warning',
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        center: true
      })
          .then(() => {
            this.deleteNoteById(note)
            this.getAllNote();
          })
          .catch(action => {
            console.log("取消删除", action)
          });
      console.log('笔记', note)
    },
    deleteNoteById(note) {
      console.log('需要删除笔记:', note)
      this.dbUtil.delete(note.id)
    },
    handleClose(done) {
      this.showSearchDialog = false;
      done();
    },
    addNote() {
      this.$router.push({ path: "/noteAdd2" })
    },
    getAllNote() {
      this.dbUtil.getAll().then(result => {
        console.log('所有数据', result);
        if (result) {
          for (let i = 0; i < result.length; i ++) {
            let obj = JSON.parse(result[i].delta)
            if (obj && obj.insert) {
              result[i].summary = this.safeSubstring(obj.insert, 0, 10)
            }
          }
          this.notes = result
        }
      }).catch(error => {
        console.error('获取所有数据失败', error);
      });
    },
    editNote(note) {
      this.$router.push({ path: '/noteAdd2', query: { id: note.id } });
      // this.$router.push({
      //   path: "/noteAdd2",
      //   params: {
      //     id: note.id
      //   }
      // })
    }
  },
  watch: {
    notes: 'filterNotes',
    searchQuery: 'filterNotes',
  },
  mounted() {
    this.filteredNotes = this.notes; // 初始化时显示所有笔记
  },
};
</script>

<style scoped>
.note-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden; /* 避免整个页面滚动 */
}

.header, .footer {
  background-color: #f5f5f5;
  padding: 10px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.actions el-button {
  margin-left: 10px;
}

.content {
  flex: 1;
  padding: 10px;
  overflow-y: auto; /* 允许内部滚动 */
}

.note-card {
  margin-bottom: 10px;
}

.note-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

note-no-content {
  font-weight: bold;
}

.note-main {
  flex: 0 0 80%; /* 主内容区占80%宽度 */
}

.note-delete {
  flex: 0 0 20%; /* 删除区占20%宽度 */
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.delete-button {
  width: 60px; /* 根据需要调整按钮大小 */
  height: 40px; /* 根据需要调整按钮大小 */
}

.note-title {
  font-size: 16px;
  font-weight: bold;
}

.note-summary {
  margin: 5px 0;
}

.note-time {
  font-size: 12px;
  color: #888;
}

.footer {
  background-color: #fff;
  padding: 10px;
}

.footer-menu {
  text-align: center;
}

.footer-menu .el-menu-item {
  line-height: 40px;
}

/* 弹出层内部容器样式 */
.search-dialog .dialog-content {
  display: flex; /* 使用Flex布局 */
  align-items: center; /* 垂直居中 */
}

/* 输入框样式 */
.search-dialog .input-container {
  flex: 0 0 80%; /* 输入框占80%宽度 */
}

/* 按钮样式 */
.search-dialog .button-container {
  flex: 0 0 20%; /* 按钮占20%宽度 */
}

/* 确保按钮填满其容器宽度 */
.search-dialog .el-button {
  width: 100%;
}
</style>